from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.hashers import make_password
from django.http import HttpResponsePermanentRedirect, HttpResponseRedirect
from django.shortcuts import render
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.urls import reverse
from django.views import View

from utils.email_send import send_register_email
from xadmin.plugins import auth
from .models import UserProfile, UserMessage
from .forms import LoginForm, RegisterForm


class CustomBackend(ModelBackend):
    """
    让用户可以用邮箱登录
    setting 里要有对应的配置
    """

    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class LoginView(View):
    """
    登录相关
    """

    def get(self, request, *args, **kwargs):
        return render(request, 'account/login.html')

    def post(self, request, *args, **kwargs):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            user_name = request.POST.get('username', '')
            password = request.POST.get('password', '')
            # 上面的 authenticate 方法 return user
            user = authenticate(username=user_name, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponsePermanentRedirect(reverse('index'))
                return render(request, 'account/login.html', {'msg': '用户未激活！'})
            return render(request, 'account/login.html', {'msg': '用户名或者密码错误！'})

        return render(request, 'account/login.html', {'form_errors': login_form.errors})


# 用户登出
class LogoutView(View):
    def get(self, request):
        logout(request)
        return HttpResponseRedirect(reverse('index'))


# 用户注册
class RegisterView(View):
    def get(self, request):
        # get 请求的时候，把验证码组件一系列的 HTML render 到 register.html 里
        register_form = RegisterForm()
        return render(request, 'account/register.html', {'register_form': register_form})

    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            email = request.POST.get('email', '')
            if UserProfile.objects.filter(email=email):
                return render(request, 'account/register.html', {'register_form': register_form, 'msg': '用户已经存在！'})
            password = request.POST.get('password', '')

            user_profile = UserProfile()
            user_profile.username = email
            user_profile.email = email
            user_profile.password = make_password(password)
            user_profile.is_active = False
            user_profile.save()

            # 注册时发送一条消息
            user_message = UserMessage()
            user_message.user = user_profile.id
            user_message.message = '欢迎注册情景学习网！'
            user_message.save()

            send_register_email(email, 'register')
            return render(request, 'common/send_success.html')

        return render(request, 'account/register.html', {'register_form': register_form})
